tab.path <- "results/table/"
tab.name <- "app_tab_g06.tex"
tab.name1 <- "app_tab_g06_wb_core.tex"
tab.name2 <- "app_tab_g06_wb_end.tex"

yvars <- c("par.onl.sh")
fcontrols <- paste0("dpost:",c(controls))

RNGkind("L'Ecuyer-CMRG")
set.seed(2022)
# d8f1127df6801a7ebe27a7f543589af6
## ParlDiv Clust 
Re$klust <- sapply(strsplit(Re$parl_div, " or "), `[`, 1)
Re$klust <- ifelse(is.na(Re$klust), paste0(Re$county, "-Resid"), Re$klust)

df_wb <- data.frame(treat = Re$treat_10, 
  dpost = Re$dpost, 
  yvar = Re$par.onl.sh,
  county = Re$county,
  klust = Re$klust,
  year = Re$year,
  pop =Re$pop,
  dist.roads = Re$dist.roads )

df_wb <- cbind(df_wb, Re[,c(controls, "gridklust", yvars, "dist.roads", "pop")])

df_wb$dptreat <- df_wb$treat * df_wb$dpost
vars <- c( "treat","dpost" ,"dptreat")
fcontrols <- paste0("dp",controls)
df_wb$wry <- df_wb$county == "wr yorkshire"
df_wb$glo <- df_wb$county == "gloucestershire"
df_wb$sur <- df_wb$county == "surrey"
df_wb$nfl <- df_wb$county == "norfolk"

for (var in c(controls, c("wry",  "sur", "nfl", "glo" ) ) ){
  print(var)
  name <- paste0("dp", var)
  df_wb[,name] <- df_wb[,var]*Re[,"dpost"]
}

vars <- c( "dptreat", "dpost", "treat")
outvars <- c( "dptreat", "dpost", "treat")
labvars <- c("DPost X March","DPost", "March")
fcontrols <- c(controls, paste0("dp",controls))


counties <- c("wry",  "sur", "nfl" ) #Have to create FEs manually for boot_lm command
Kont <- c(fcontrols, counties)
m1.wb <- felm(as.formula(RegFor( y = yvars[1] , x = c(vars, Kont) ,
      FE = "0" , IV="0", clust = "0" )),
           data=subset(df_wb, county != "gloucestershire" 
           )) 
set.seed(2022)
boot_lm1 <- boottest(
  m1.wb,  clustid = "klust",
  param = "dptreat", B = 9999
) 
set.seed(2022)
boot_lm1_treat <- boottest(
  m1.wb,  clustid = "klust",
  param = "treatTRUE",  B = 9999
)
set.seed(2022)
boot_lm1_post <- boottest(
  m1.wb,  clustid = "klust",
  param = "dpostTRUE",  B = 9999
)

counties <- c("wry",  "sur", "glo") #Have to create FEs manually for boot_lm command
Kont <- c(fcontrols, counties)
m2.wb <- felm(as.formula(RegFor( y = yvars[1] , x = c(vars, Kont) ,
      FE = "0" , IV="0", clust = "0" )),
           data=subset(df_wb, county != "norfolk"
           ))
set.seed(2022)
boot_lm2 <- boottest(
  m2.wb,  clustid = "klust",
  param = "dptreat", B = 9999
)  
set.seed(2022)

boot_lm2_treat <- boottest(
  m2.wb,  clustid = "klust",
  param = "treatTRUE",  B = 9999
)
set.seed(2022)

boot_lm2_post <- boottest(
  m2.wb,  clustid = "klust",
  param = "dpostTRUE",  B = 9999
)

counties <- c("wry",  "nfl", "glo") #Have to create FEs manually for boot_lm command
Kont <- c(fcontrols, counties)
m3.wb <- felm(as.formula(RegFor( y = yvars[1] , x = c(vars, Kont) ,
      FE = "0" , IV="0", clust = "0" )),
           data=subset(df_wb, county != "surrey" 
            ) )

boot_lm3 <- boottest(
  m3.wb,  clustid = "klust",
  param = "dptreat", B = 9999
)
set.seed(2022)
boot_lm3_treat <- boottest(
  m3.wb,  clustid = "klust",
  param = "treatTRUE",  B = 9999
)
set.seed(2022)
boot_lm3_post <- boottest(
  m3.wb,  clustid = "klust",
  param = "dpostTRUE",  B = 9999
)
counties <- c("sur",  "nfl", "glo") #Have to create FEs manually for boot_lm command
Kont <- c(controls, counties)
m4.wb <- felm(as.formula(RegFor( y = yvars[1] , x = c(vars, Kont) ,
      FE = "0" , IV="0", clust = "0" )),
           data=subset(df_wb, county != "wr yorkshire"
           ) )
set.seed(2022)
boot_lm4 <- boottest(
  m4.wb,  clustid = "klust",
  param = "dptreat", B = 9999
)
set.seed(2022)

boot_lm4_treat <- boottest(
  m4.wb,  clustid = "klust",
  param = "treatTRUE",  B = 9999
)
set.seed(2022)

boot_lm4_post <- boottest(
  m4.wb,  clustid = "klust",
  param = "dpostTRUE",  B = 9999
)
getwd()
regstoadd <- list(m1.wb,m2.wb, m3.wb,m4.wb)

MSd <- function(variable){
  x1 <- round(mean(variable, na.rm = TRUE), 2)
  x2<-  round(sd(variable, na.rm = TRUE), 2)
  return(c(x1,x2))
}

Stats <- rbind(MSd(Re[,yvars[1]]),
  MSd(Re[Re$county != "gloucestershire",yvars[1]]) ,
  MSd(Re[Re$county != "norfolk",yvars[1]]) ,
  MSd(Re[Re$county != "surrey",yvars[1]]),
  MSd(Re[Re$county != "wr yorkshire",yvars[1]]))
####OUT
add.lines <- list(AddLines( 5, "County Dropped", c(LMc("GLO"), LMc("NFK"), LMc("SUR"), LMc("WRY"))),
                  AddLines( 5, "Mean dep. var." , Stats[,1] ),
                  AddLines( 5, "Sd dep. var." , Stats[,2] )
                 )

# fileConn<-file(paste0(tab.path,tab.name))
# print(fileConn)
# writeLines(stargazer(regstoadd,
#                      float = FALSE ,
#                      keep= outvars,
#                      order = outvars ,
#                      covariate.labels= labvars ,
#                      star.cutoffs = c(0.1099, 0.0599, 0.0199) ,
#                      digits.extra = 0,
#                      multicolumn=F,#
#                      #column.sep.width="10pt",
#                      dep.var.caption = paste("Share of Local Electors" ),
#                      dep.var.labels.include = F,
#                      font.size = "footnotesize",
#                      omit.table.layout = "n",
#                      align =T,
#                      add.lines = add.lines,
#                      digits = 3,
#                      intercept.top = T,
#                      intercept.bottom = F,
#                      keep.stat = c("rsq" , "n") ,
#                      omit.stat = c("res.dev","ser") ),
#            fileConn)
# close(fileConn)


## Wild Cluster Output

 
## Spit stars function

SpitStars <- function(x){
  s1 <- ifelse((x <=0.109), "*","")
  s2 <- ifelse((x <=0.059), "*","")
  s3 <- ifelse((x <=0.011), "*","")
  out <- paste0(s1,s2,s3)
  return(out)
}
## Main coef
bsdp <- round(c(coefficients(m1.wb)["dptreat"],
    coefficients(m2.wb)["dptreat"],
    coefficients(m3.wb)["dptreat"],
    coefficients(m4.wb)["dptreat"]
), 3)
tstat <- round(c(boot_lm1$t_stat, boot_lm2$t_stat, boot_lm3$t_stat, boot_lm4$t_stat), 3)
pval <- round(c(boot_lm1$p_val, boot_lm2$p_val, boot_lm3$p_val, boot_lm4$p_val), 3)
st <- SpitStars(pval)
outcoef <- paste0("$", sprintf("%.3f",bsdp), "^{",st, "}$")
outtstat <- paste0("[", tstat, "]")
outpval <- paste0("[", sprintf("%.2f", pval), "]")

## Treat
bsdp_t <- round(c(coefficients(m1.wb)["treatTRUE"],
    coefficients(m2.wb)["treatTRUE"],
    coefficients(m3.wb)["treatTRUE"],
    coefficients(m4.wb)["treatTRUE"]
), 3)

tstat_t <- round(c(boot_lm1_treat$t_stat, boot_lm2_treat$t_stat, boot_lm3_treat$t_stat, boot_lm4_treat$t_stat), 3)
pval_t <- round(c(boot_lm1_treat$p_val, boot_lm2_treat$p_val, boot_lm3_treat$p_val, boot_lm4_treat$p_val), 2)
st_t <- SpitStars(pval_t)
outcoef_t <- paste0("$", sprintf("%.3f",bsdp_t), "^{",st_t, "}$")
outtstat_t <- paste0("[", tstat_t, "]")
outpval_t <- paste0("[", sprintf("%.2f", pval_t), "]")

## Dpost
bsdp_p <- round(c(coefficients(m1.wb)["dpostTRUE"],
    coefficients(m2.wb)["dpostTRUE"],
    coefficients(m3.wb)["dpostTRUE"],
    coefficients(m4.wb)["dpostTRUE"]
), 3)
tstat_p <- round(c(boot_lm1_post$t_stat, boot_lm2_post$t_stat, boot_lm3_post$t_stat, boot_lm4_post$t_stat), 3)
pval_p <- round(c(boot_lm1_post$p_val, boot_lm2_post$p_val, boot_lm3_post$p_val, boot_lm4_post$p_val), 2)
st_p <- SpitStars(pval_p)
outcoef_p <- paste0("$", sprintf("%.3f",bsdp_p), "^{",st_p, "}$")
outtstat_p <- paste0("[", tstat_p, "]")
outpval_p <-  paste0("[", sprintf("%.2f", pval_p), "]")
##Output core table
KoreTab <- data.frame(rbind(
  c("DPost X March", outcoef),
  c("", outpval), 
  vector(mode="character", length=5), #Empty line
  c("DPost", outcoef_p),
  c("", outpval_p),  
  vector(mode="character", length=5), #Empty line
  c("March", outcoef_t),
  c("", outpval_t) 
))

write.table(KoreTab,
    file=paste0(tab.path, tab.name1),
    sep=" & ", 
    quote =  FALSE, 
    col.names = FALSE ,
    row.names = FALSE, 
    eol = " \\\\ \n ")

## Output end of table

Stats <- rbind(  MSd(Re[Re$county != "gloucestershire",yvars[1]]) ,
  MSd(Re[Re$county != "norfolk",yvars[1]]) ,
  MSd(Re[Re$county != "surrey",yvars[1]]),
  MSd(Re[Re$county != "wr yorkshire",yvars[1]]))
####OUT

x <- c(
  summary(m1.wb)$r.squared,
  summary(m2.wb)$r.squared,
  summary(m3.wb)$r.squared,
  summary(m4.wb)$r.squared)
Rs <- round(x,3)

Ns <- c(m1.wb$N, m2.wb$N, m3.wb$N, m4.wb$N)

####OUT
EndTab<- rbind(
AddLines( 5, "County Dropped", c(LMc("GLO"), LMc("NFK"), LMc("SUR"), LMc("WRY"))),
                  AddLines( 5, "Mean dep. var." , Stats[,1] ),
                  AddLines( 5, "Sd dep. var." , Stats[,2] ),
c("Observations", Ns), 
c("$R^2$", Rs)
)
write.table(EndTab,
    file=paste0(tab.path, tab.name2),
    sep=" & ", 
    quote =  FALSE, 
    col.names = FALSE ,
    row.names = FALSE, 
    eol = " \\\\ \n ")

rm(list=
    setdiff(ls()[sapply(ls(), function(x) any(class(get(x)) == 'data.frame'))],
    c("Re","Ind")))
